package com.yupi.springbootinit.controller;

import cn.hutool.core.io.FileUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.google.gson.Gson;
import com.yupi.springbootinit.annotation.AuthCheck;
import com.yupi.springbootinit.common.BaseResponse;
import com.yupi.springbootinit.common.DeleteRequest;
import com.yupi.springbootinit.common.ErrorCode;
import com.yupi.springbootinit.common.ResultUtils;
import com.yupi.springbootinit.config.ThreadPoolConfig;
import com.yupi.springbootinit.constant.CommonConstant;
import com.yupi.springbootinit.constant.UserConstant;
import com.yupi.springbootinit.exception.BusinessException;
import com.yupi.springbootinit.exception.ThrowUtils;
import com.yupi.springbootinit.manager.AiManager;
import com.yupi.springbootinit.manager.RateLimiterManager;
import com.yupi.springbootinit.model.dto.chart.*;
import com.yupi.springbootinit.model.entity.Chart;
import com.yupi.springbootinit.model.entity.User;
import com.yupi.springbootinit.model.enums.ChartEnum;
import com.yupi.springbootinit.model.vo.BiResponse;
import com.yupi.springbootinit.service.ChartService;
import com.yupi.springbootinit.service.UserService;
import com.yupi.springbootinit.utils.ExcelUtils;
import com.yupi.springbootinit.utils.SqlUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ThreadPoolExecutor;

/**
 * 帖子接口
 *
 * @author <a href="https://github.com/liyupi">程序员鱼皮</a>
 * @from <a href="https://yupi.icu">编程导航知识星球</a>
 */
@RestController
@RequestMapping("/chart")
@Slf4j
public class ChartController {

    @Resource
    private ChartService chartService;

    @Resource
    private UserService userService;

    @Resource
    private AiManager aiManager;

    @Resource
    private RateLimiterManager rateLimiterManager;

    @Resource
    private ThreadPoolExecutor threadPoolExecutor;

    private final static Gson GSON = new Gson();

    // region 增删改查

    /**
     * 创建
     *
     * @param chartAddRequest
     * @param request
     * @return
     */
    @PostMapping("/add")
    public BaseResponse<Long> addChart(@RequestBody ChartAddRequest chartAddRequest, HttpServletRequest request) {
        if (chartAddRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        Chart chart = new Chart();
        BeanUtils.copyProperties(chartAddRequest, chart);
        User loginUser = userService.getLoginUser(request);
        chart.setUserId(loginUser.getId());
        boolean result = chartService.save(chart);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
        long newChartId = chart.getId();
        return ResultUtils.success(newChartId);
    }

    /**
     * 删除
     *
     * @param deleteRequest
     * @param request
     * @return
     */
    @PostMapping("/delete")
    public BaseResponse<Boolean> deleteChart(@RequestBody DeleteRequest deleteRequest, HttpServletRequest request) {
        if (deleteRequest == null || deleteRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        User user = userService.getLoginUser(request);
        long id = deleteRequest.getId();
        // 判断是否存在
        Chart oldChart = chartService.getById(id);
        ThrowUtils.throwIf(oldChart == null, ErrorCode.NOT_FOUND_ERROR);
        // 仅本人或管理员可删除
        if (!oldChart.getUserId().equals(user.getId()) && !userService.isAdmin(request)) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
        }
        boolean b = chartService.removeById(id);
        return ResultUtils.success(b);
    }

    /**
     * 更新（仅管理员）
     *
     * @param chartUpdateRequest
     * @return
     */
    @PostMapping("/update")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Boolean> updateChart(@RequestBody ChartUpdateRequest chartUpdateRequest) {
        if (chartUpdateRequest == null || chartUpdateRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        Chart chart = new Chart();
        BeanUtils.copyProperties(chartUpdateRequest, chart);
        long id = chartUpdateRequest.getId();
        // 判断是否存在
        Chart oldChart = chartService.getById(id);
        ThrowUtils.throwIf(oldChart == null, ErrorCode.NOT_FOUND_ERROR);
        boolean result = chartService.updateById(chart);
        return ResultUtils.success(result);
    }

    /**
     * 根据 id 获取
     *
     * @param id
     * @return
     */
    @GetMapping("/get")
    public BaseResponse<Chart> getChartById(long id, HttpServletRequest request) {
        if (id <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        Chart chart = chartService.getById(id);
        if (chart == null) {
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR);
        }
        return ResultUtils.success(chart);
    }

    /**
     * 分页获取列表（封装类）
     *
     * @param chartQueryRequest
     * @param request
     * @return
     */
    @PostMapping("/list/page")
    public BaseResponse<Page<Chart>> listChartByPage(@RequestBody ChartQueryRequest chartQueryRequest,
            HttpServletRequest request) {
        long current = chartQueryRequest.getCurrent();
        long size = chartQueryRequest.getPageSize();
        // 限制爬虫
        ThrowUtils.throwIf(size > 20, ErrorCode.PARAMS_ERROR);
        Page<Chart> chartPage = chartService.page(new Page<>(current, size),
                getQueryWrapper(chartQueryRequest));
        return ResultUtils.success(chartPage);
    }

    /**
     * 分页获取当前用户创建的资源列表
     *
     * @param chartQueryRequest
     * @param request
     * @return
     */
    @PostMapping("/my/list/page")
    public BaseResponse<Page<Chart>> listMyChartByPage(@RequestBody ChartQueryRequest chartQueryRequest,
            HttpServletRequest request) {
        if (chartQueryRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        User loginUser = userService.getLoginUser(request);
        chartQueryRequest.setUserId(loginUser.getId());
        long current = chartQueryRequest.getCurrent();
        long size = chartQueryRequest.getPageSize();
        // 限制爬虫
        ThrowUtils.throwIf(size > 20, ErrorCode.PARAMS_ERROR);
        Page<Chart> chartPage = chartService.page(new Page<>(current, size),
                getQueryWrapper(chartQueryRequest));
        return ResultUtils.success(chartPage);
    }

    // endregion

    /**
     * 编辑（用户）
     *
     * @param chartEditRequest
     * @param request
     * @return
     */
    @PostMapping("/edit")
    public BaseResponse<Boolean> editChart(@RequestBody ChartEditRequest chartEditRequest, HttpServletRequest request) {
        if (chartEditRequest == null || chartEditRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        Chart chart = new Chart();
        BeanUtils.copyProperties(chartEditRequest, chart);
        User loginUser = userService.getLoginUser(request);
        long id = chartEditRequest.getId();
        // 判断是否存在
        Chart oldChart = chartService.getById(id);
        ThrowUtils.throwIf(oldChart == null, ErrorCode.NOT_FOUND_ERROR);
        // 仅本人或管理员可编辑
        if (!oldChart.getUserId().equals(loginUser.getId()) && !userService.isAdmin(loginUser)) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
        }
        boolean result = chartService.updateById(chart);
        return ResultUtils.success(result);
    }

    /**
     * 获取查询包装类
     *
     * @param chartQueryRequest
     * @return
     */
    private QueryWrapper<Chart> getQueryWrapper(ChartQueryRequest chartQueryRequest) {
        QueryWrapper<Chart> queryWrapper = new QueryWrapper<>();
        if (chartQueryRequest == null) {
            return queryWrapper;
        }
        Long id = chartQueryRequest.getId();
        String goal = chartQueryRequest.getGoal();
        String chartType = chartQueryRequest.getChartType();
        Long userId = chartQueryRequest.getUserId();
        String sortField = chartQueryRequest.getSortField();
        String sortOrder = chartQueryRequest.getSortOrder();
        String name = chartQueryRequest.getName();

        queryWrapper.eq(id != null && id > 0, "id", id);
        queryWrapper.like(StringUtils.isNotBlank(name), "name", name);
        queryWrapper.eq(StringUtils.isNotBlank(goal), "goal", goal);
        queryWrapper.eq(StringUtils.isNotBlank(chartType), "chartType", chartType);
        queryWrapper.eq(ObjectUtils.isNotEmpty(userId), "userId", userId);
        queryWrapper.eq("isDelete", false);
        queryWrapper.orderBy(SqlUtils.validSortField(sortField), sortOrder.equals(CommonConstant.SORT_ORDER_ASC),
                sortField);
        return queryWrapper;
    }


    /**
     * 文件上传
     *
     * @param multipartFile
     * @param genChartByAiRequest
     * @param request
     * @return
     */
    @PostMapping("/gen/async")
    public BaseResponse<BiResponse> genChartByAiAsync(@RequestPart("file") MultipartFile multipartFile,
                                                 GenChartByAiRequest genChartByAiRequest, HttpServletRequest request) {
        String chartData = genChartByAiRequest.getChartData();
        String chartType = genChartByAiRequest.getChartType();
        String goal = genChartByAiRequest.getGoal();
        String name = genChartByAiRequest.getName();

        // 1. 参数检验
        // 判空
        ThrowUtils.throwIf(StringUtils.isEmpty(goal), ErrorCode.PARAMS_ERROR, "目标不能为空");
        ThrowUtils.throwIf(StringUtils.isNotEmpty(name) && name.length() > 100, ErrorCode.PARAMS_ERROR, "目标不能为空");
        // 文件大小检验
        final long _1_MB = 1024 * 1024;
        long fileSize = multipartFile.getSize();
        ThrowUtils.throwIf(fileSize > _1_MB, ErrorCode.OPERATION_ERROR, "文件太大");
        //文件格式检验
        List<String> supportSuffix = Arrays.asList("xlsx");
        String fileSuffix = FileUtil.getSuffix(multipartFile.getOriginalFilename());
        ThrowUtils.throwIf(!supportSuffix.contains(fileSuffix), ErrorCode.OPERATION_ERROR, "不支持" + fileSuffix + "这个格式");


        // 2. 给每个用户限流
        // 当前用户
        User loginUser = userService.getLoginUser(request);
        rateLimiterManager.rateLimiterByKey("genChartByAi:" + loginUser.getId());


        // 3. 组装数据
        StringBuilder sb = new StringBuilder();
        sb.append("分析需求：").append("\n");
        String myGoal = goal;
        if (chartType != null) {
            myGoal += "，请使用" + chartType;
        }
        sb.append(myGoal);
        sb.append("原始数据：").append("\n");
        CsvDataDTO csvDataDTO = ExcelUtils.Excel2Csv(multipartFile);
        ThrowUtils.throwIf(csvDataDTO == null, ErrorCode.PARAMS_ERROR, "分析数据不能为空");
        String csv = csvDataDTO.getCsv();
        sb.append(csv).append("\n");

        // 1. 先将用户的数据保存到数据库，status = wait
        Chart chart = new Chart();
        chart.setName(name);
        chart.setGoal(goal);
        chart.setChartData(csv);
        chart.setChartType(chartType);
        chart.setStatus(ChartEnum.WAIT.getValue());
        chart.setUserId(loginUser.getId());
        boolean isSuccess = chartService.save(chart);
        ThrowUtils.throwIf(!isSuccess, ErrorCode.SYSTEM_ERROR, "图标保存失败");
        // 2. 开启线程异步调用ai status = running -> succeed | failed
        CompletableFuture.runAsync(() -> {
            Thread currentThread = Thread.currentThread();
            log.info("线程" + currentThread.getName() + "开始调用ai接口");
            Chart updateChart = new Chart();
            updateChart.setId(chart.getId());
            updateChart.setStatus(ChartEnum.RUNNING.getValue());
            boolean isUpdate = chartService.updateById(updateChart);
            if (!isUpdate) {
                handleChartUpdateError(chart.getId(), "更新图标失败");
            }
            // 发送给ai
            final long modelId = 1659171950288818178L;
            String content = aiManager.doChat(csv, modelId);
            // 解析数据
            String[] split = content.split("【【【【【");
            if (split.length < 3) {
                handleChartUpdateError(chart.getId(), "Ai生成失败");
                throw new BusinessException(ErrorCode.OPERATION_ERROR, "ai生成失败");
            }
            String genChart = split[1].trim();
            String genResult = split[2].trim();

//            // 简单筛选一下
            int firstIndex = genChart.indexOf("{");
            int lastIndex = genChart.lastIndexOf("}");

            if (firstIndex != -1 && lastIndex != -1 && lastIndex > firstIndex) {
                genChart = genChart.substring(firstIndex, lastIndex + 1);
            } else {
                handleChartUpdateError(chart.getId(), "Ai生成失败");
                throw new BusinessException(ErrorCode.OPERATION_ERROR, "ai生成失败");
            }
            // 成功
            Chart resultChart = new Chart();
            resultChart.setId(chart.getId());
            resultChart.setGenChart(genChart);
            resultChart.setGenResult(genResult);
            resultChart.setStatus(ChartEnum.SUCCEED.getValue());
            boolean result = chartService.updateById(resultChart);
            if (!result) {
                handleChartUpdateError(chart.getId(), "更新图标成功状态失败");
            }
            log.info("线程" + currentThread.getName() + "完成调用ai接口");
        }, threadPoolExecutor);
        // 3. 返回给前端
        BiResponse biResponse = new BiResponse();
        biResponse.setCharId(chart.getId());
        return ResultUtils.success(biResponse);
    }

    private void handleChartUpdateError(long chartId, String execMessage) {
        Chart chart = new Chart();
        chart.setId(chartId);
        chart.setStatus(ChartEnum.FAILED.getValue());
        chart.setExecMessage(execMessage);
        boolean isUpdate = chartService.updateById(chart);
        if (!isUpdate) {
            log.error("更新图标失败状态失败" + chartId + ", " + execMessage);
        }
    }

    /**
     * 文件上传
     *
     * @param multipartFile
     * @param genChartByAiRequest
     * @param request
     * @return
     */
    @PostMapping("/gen")
    public BaseResponse<BiResponse> genChartByAi(@RequestPart("file") MultipartFile multipartFile,
                                           GenChartByAiRequest genChartByAiRequest, HttpServletRequest request) {
        String chartData = genChartByAiRequest.getChartData();
        String chartType = genChartByAiRequest.getChartType();
        String goal = genChartByAiRequest.getGoal();
        String name = genChartByAiRequest.getName();
        // 1. 参数检验
        // 判空
        ThrowUtils.throwIf(StringUtils.isEmpty(goal), ErrorCode.PARAMS_ERROR, "目标不能为空");
        ThrowUtils.throwIf(StringUtils.isNotEmpty(name) && name.length() > 100, ErrorCode.PARAMS_ERROR, "目标不能为空");
        // 文件大小检验
        final long _1_MB = 1024 * 1024;
        long fileSize = multipartFile.getSize();
        ThrowUtils.throwIf(fileSize > _1_MB, ErrorCode.OPERATION_ERROR, "文件太大");
        //文件格式检验
        List<String> supportSuffix = Arrays.asList("xlsx");
        String fileSuffix = FileUtil.getSuffix(multipartFile.getOriginalFilename());
        ThrowUtils.throwIf(!supportSuffix.contains(fileSuffix), ErrorCode.OPERATION_ERROR, "不支持" + fileSuffix + "这个格式");
        // 2. 给每个用户限流
        // 当前用户
        User loginUser = userService.getLoginUser(request);
        rateLimiterManager.rateLimiterByKey("genChartByAi:" + loginUser.getId());
        // 3. 组装数据
        StringBuilder sb = new StringBuilder();
        sb.append("分析需求：").append("\n");
        String myGoal = goal;
        if (chartType != null) {
            myGoal += "，请使用" + chartType;
        }
        sb.append(myGoal);
        sb.append("原始数据：").append("\n");
        CsvDataDTO csvDataDTO = ExcelUtils.Excel2Csv(multipartFile);
        ThrowUtils.throwIf(csvDataDTO == null, ErrorCode.PARAMS_ERROR, "分析数据不能为空");
        String csv = csvDataDTO.getCsv();
        sb.append(csv).append("\n");

        // 发送给ai
        final long modelId = 1659171950288818178L;
        String content = aiManager.doChat(csv, modelId);
        // 解析数据
        String[] split = content.split("【【【【【");
        if (split.length < 3) {
            throw new BusinessException(ErrorCode.OPERATION_ERROR, "ai生成失败");
        }
        String genChart = split[1].trim();
        String genResult = split[2].trim();
        // 保存到数据库
         Chart chart = new Chart();
        chart.setName(name);
        chart.setGoal(goal);
        chart.setChartData(csv);
        chart.setChartType(chartType);
        chart.setGenChart(genChart);
        chart.setGenResult(genResult);
        chart.setUserId(loginUser.getId());
        chartService.save(chart);

        // TODO 分表存储
//        ChartTableInfoDTO chartTableInfo = new ChartTableInfoDTO();
//        String tableName = "chart_" + chart.getId();
//        List<String> head = csvDataDTO.getChartHead();
//        chartTableInfo.setTableName(tableName);
//        chartTableInfo.setColumnsName(head);
//        chartTableInfo.setData(csvDataDTO.getChartBody());
//        // 建表 和插入表
//        chartService.createAndInsertChartTable(chartTableInfo);
        BiResponse biResponse = new BiResponse();
        biResponse.setGenChart(genChart);
        biResponse.setCharId(chart.getId());
        biResponse.setGenResult(genResult);
        return ResultUtils.success(biResponse);
    }

}
